package graphics;

import javax.microedition.lcdui.Font;
import javax.microedition.lcdui.Graphics;

public class MultiLineText {
	
	private static int MAX_WIDTH = 200;
	private int y;
	private String title = null;

	public MultiLineText(int aY, Graphics graphics) {
		y = aY;
	}

	public void repaint(Graphics graphics, int color) {
		if (title == null) {
			return;
		}
		
		Font f = graphics.getFont();
		graphics.setColor(BootColor.BLACK);
		graphics.fillRect(0, y, 240, 3 * f.getHeight());
		
		graphics.setColor(color);
		
		
		if ((f.stringWidth(title)) > MAX_WIDTH) {
			String[] lines = getLines(title, f);
			graphics.drawString(lines[0], 
					120, y + f.getHeight() / 2, Graphics.TOP|Graphics.HCENTER);
			graphics.drawString(lines[1], 
					120, y + f.getHeight() * 3/2, Graphics.TOP|Graphics.HCENTER);
		} else {						
			graphics.drawString(title, 
					120, y + f.getHeight(), Graphics.TOP|Graphics.HCENTER);
		}

	}
	
	private String[] getLines(String input, Font f) {
		String[] result = new String[] {input, null};

		
		while (f.stringWidth(result[0]) > MAX_WIDTH) {
			int index = result[0].lastIndexOf(' ');
			if (result[1] == null) {
				result[1] = result[0].substring(index);				
			} else {
				result[1] = result[0].substring(index) + result[1];	
			}
			result[0] = result[0].substring(0, index).trim();
		}
		result[1] = result[1].trim();
		
		if (f.stringWidth(result[1]) < MAX_WIDTH) {
			return result;
		}
		while (f.stringWidth(result[1] + " [...]") > MAX_WIDTH) {
			result[1] = result[1].substring(0, result[1].lastIndexOf(' '));
		}		
		result[1] = result[1] + " [...]";

		return result;
	}

	public void setContent(String aTitle) {
		title  = aTitle;
	}
}
